<template lang="pug">
.page
  .CustomerSalaryDetail
    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(:columns="setThead" :data="tableData" :stripe="true" ref="customerSalaryTable" @on-selection-change="handleOnSelectChange")
        .clearfix.font-16(slot="header")
          .table-title-lefttxt.pull-left
            |合计
            span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
            |条
          .pull-right.table-title-btns
            //- Button.ml-10(v-if="hasImport" type="info" @click="handleShowBatchImportModal") 导入
            Button(type="info" v-if='hasExport'  @click="handleExport") 导出
            //- Button.ml-10(v-if="hasDelete" type="warning" @click="handleDelete") 删除

        template(slot-scope="{ row, index }" slot="action") ￥{{row.realSalaryTotal}}

        .clearfix.pl-20.pr-20(slot="footer")
          Page(
            :current="tableComone.pageIndex"
            :total="tableComone.totalRows"
            @on-change="onChangePage"
            @on-page-size-change="onpageSizeChange"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )
    //- 批量导入花名册弹窗
    BatchImportModal(ref="BatchImportModal" @handleMaxSizeTen="handleMaxSizeTen" @query="searchFn")
</template>

<script>
import { CustomerSalaryApi } from '@/api/CustomerSalary.api.js'
import { EmployeeSalaryApi } from '@/api/EmployeeSalary.api.js'
import { Common } from '@/utils/common.js'
import { salaryDetailTheadObj } from './CStableHead.js'
import _cloneDeep from 'clone-deep'
import BatchImportModal from './modal/batchImportModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')
export default {
  name: 'CustomerSalaryDetail',

  components: {
    BatchImportModal
  },

  data () {
    return {
      salaryId: '',
      salaryMonth: '',
      tableColumns: _cloneDeep(salaryDetailTheadObj),
      // thead: ['selection'],
      thead: ['selection', 'customerName', 'declareUnitName', 'salaryMonth', 'satrtEnd', 'deductionTypeName', 'payDate', 'incomeTypeName', 'name', 'identityCardNO', 'bankName', 'bankAccountNo', 'salaryBank', 'phone', 'shouldSalaryTotal', 'socialSecurityDeduct', 'providentFundDeduct', 'specialDeduct', 'otherDeduct', 'incomeTax', 'incomeTaxDiff', 'serviceCharge', 'afterTaxDeduct', 'historyDeduct', 'description', 'realSalaryTotal', 'totalShouldSalaryTotal', 'totalSocialSecurityDeduct', 'totalProvidentFundDeduct', 'totalSpecialDeduct', 'totalReductionFee', 'totalOtherDeduct','taxableIncome', 'totalIncomeDeduct', 'prePayIncomeDeduct'],
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      formData: {
        name: '',
        month: ''
      },
      downLoadUrl: ''
    }
  },

  computed: {
    setThead () {      
      return Common.getTableColumns(this.thead, this.tableColumns)
    },

    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 删除
    hasDelete () {
      return this.actionArr.indexOf('DeleteEmployeeSalary') > -1
    },
    // 导入
    hasImport () {
      return this.actionArr.indexOf('ImportEmployeeSalary') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    
  },

  watch: {
  },

  mounted () {
    this.salaryId = this.$route.query.id
    this.salaryMonth = this.$route.query.month
    this.query()
    this.downLoadUrl = '/api/EmployeeSalary/Export?SalaryGUID=' + this.salaryId + '&SalaryMonth=' + this.salaryMonth
  },

  methods: {
    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        SalaryGUID: this.salaryId,
        SalaryMonth: this.salaryMonth,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await EmployeeSalaryApi.getList(params)
      console.log('客户薪资res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    handleExportData (ref, filename) {
      Common.handleExportData(this.$refs.customerSalaryTable, '客户薪资明细')
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 导出
    // async handleExport () {
    //   var params = {
    //     ids: this.selectedEmployeeId.join(','),
    //     salaryGUID: this.$route.query.id,
    //     salaryMonth: this.$route.query.month
    //   }
    //   let res = await EmployeeSalaryApi.export(params)
    //   console.log('客户薪资导出res: ', res)
    //   if (res.status === 200 && res.data.success) {
    //     // this.$Message.success(res.data)
    //     let fileName = '客户薪资明细.xls'
    //     // 获取文件名
    //     let objectUrl = URL.createObjectURL(new Blob([res.data],{type: 'application/octet-stream'}))
    //     // 文件地址
    //     const link = document.createElement('a')
    //     link.download = fileName
    //     link.href = objectUrl
    //     link.click()
    //     // this.templateModal = false
    //   } else {
    //     this.$Message.error({
    //       content: '导出失败',
    //       // duration: 0,
    //       closable: true
    //     })
    //   }
    // }
    async handleExport () {
      var params = {
        ids: this.selectedEmployeeId.join(','),
        salaryGUID: this.$route.query.id,
        salaryMonth: this.$route.query.month
      }
      let res = await EmployeeSalaryApi.export(params)
      console.log('客户薪资导出res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.data)
        window.open(baseUrl + res.data.data, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 批量删除
    async handleDelete () {
      var params = {
        id: this.selectedEmployeeId.join(','),
        year: this.$moment(this.tableData[0].salaryMonth).format('YYYY')
      }
      console.log('🌈', params)
      let res = await EmployeeSalaryApi.delete(params)
      console.log('删除res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.tableComone.pageIndex = 1
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 批量导入-显示弹窗
    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.show()
      this.$refs.BatchImportModal.file = null
      this.$refs.BatchImportModal.errorData.isError = false
      this.$refs.BatchImportModal.year = this.$moment(this.tableData[0].salaryMonth).format('YYYY')
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  }
}
</script>

<style lang="less" scope>
</style>
